package cn.kuporo.seckill.activity.application.lintener;

import cn.hutool.core.util.StrUtil;
import cn.kuporo.seckill.activity.application.cache.SeckillActivityCacheService;
import cn.kuporo.seckill.activity.application.cache.SeckillActivityListCacheService;
import cn.kuporo.seckill.activity.domain.event.SeckillActivityEvent;
import cn.kuporo.seckill.common.constants.MQConstants;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

/**
 * @author: kuporo
 * @since: 2025/7/9
 * @description:
 */
@Component
@ConditionalOnProperty(name = "message.mq.type", havingValue = "rocketmq")
@RocketMQMessageListener(consumerGroup = MQConstants.EVENT_ACTIVITY_CONSUMER_GROUP, topic = MQConstants.TOPIC_EVENT_ROCKETMQ_ACTIVITY)
@RequiredArgsConstructor
@Slf4j
public class SeckillActivityRocketMQEventHandler implements RocketMQListener<String> {
    private final SeckillActivityCacheService seckillActivityCacheService;
    private final SeckillActivityListCacheService seckillActivityListCacheService;
    @Override
    public void onMessage(String message) {
        log.info("rocketmq-activityEvent-接收活动事件-{}", message);
        if (StrUtil.isEmpty(message)){
            log.info("rocketmq-activityEvent-事件参数错误" );
            return;
        }
        SeckillActivityEvent seckillActivityEvent = this.getEventMessage(message);
        seckillActivityCacheService.tryUpdateSeckillActivityCacheByLock(seckillActivityEvent.getId(), false);
        seckillActivityListCacheService.tryUpdateSeckillActivityCacheByLock(seckillActivityEvent.getStatus(), false);

    }

    private SeckillActivityEvent getEventMessage(String message) {
        JSONObject jsonObject = JSONObject.parseObject(message);
        String eventStr = jsonObject.getString(MQConstants.MSG_KEY);
        return JSONObject.parseObject(eventStr, SeckillActivityEvent.class);
    }
}
